package com.siruier.boss.ui.utils;

import java.nio.charset.StandardCharsets;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;

public class RequestAesUtil {
    private static final AES aes;
    private static final String KEY = "7F3E4A109890FF6A";

    static {
        aes = new AES(Mode.ECB, Padding.PKCS5Padding, KEY.getBytes(StandardCharsets.UTF_8));
    }

    public static String decrypt(String encryptData) {
        return aes.decryptStr(encryptData, CharsetUtil.CHARSET_UTF_8);
    }

    public static String encrypt(String data) {
        return encrypt(data.getBytes(StandardCharsets.UTF_8), KEY.getBytes(StandardCharsets.UTF_8));
//        return aes.encryptBase64(data.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 字节数组转成16进制字符串
     **/
    public static String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length * 2);
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            // 整数转成十六进制表示
            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString(); // 转成字符串

    }

    //加密
    public static String encrypt(byte[] data, byte[] key) {
        try {
            Key k = toKey(key);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, k);
            return Base64.encode(cipher.doFinal(data));
        } catch (Exception e) {
            Logger.e(e);
            return "";
        }
    }

    public static Key toKey(byte[] key) {
        return new SecretKeySpec(key, "AES");
    }
}
